// 接收客户端 request，并将 request 中带的 header 写入 response header
// 读取当前系统的环境变量中的 VERSION 配置，并写入 response header
// Server 端记录访问日志包括客户端 IP，HTTP 返回码，输出到 server 端的标准输出
// 当访问 localhost/healthz 时，应返回 200

package main

import (
	"io"
	"net/http"
	"log"
	"os"
	//"strings"
	"time"
)

func main() {
	healthzFuncHandler := http.HandlerFunc(healthzFunc)
	http.Handle("/healthz", middlewareHandler(healthzFuncHandler))

	err := http.ListenAndServe(":80", nil)

	if err != nil {
		log.Fatal(err)
	}
}

func middlewareHandler(next http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		start := time.Now()
		next.ServeHTTP(w, r)
		log.Printf("%s %s [%s] %s %v", r.RemoteAddr, "-", start, r.URL.Path, 200)
		//log.Printf("%s %s [%s] %s %s", r.RemoteAddr, "-", start, r.URL.Path, r.Response.Status)
	})
}


func healthzFunc(w http.ResponseWriter, r *http.Request){
	w.Header().Set("X-VERSION", os.Getenv("VERSION"))
	for k, v := range r.Header {
		w.Header().Set(k, v[0])
	}
	io.WriteString(w, "ok")
}
